package com.hboxs.asl.qcloudLVB.controller.app;

import com.gexin.fastjson.JSONObject;
import com.hboxs.asl.*;
import com.hboxs.asl.Order;
import com.hboxs.asl.controller.app.BaseController;
import com.hboxs.asl.entity.*;
import com.hboxs.asl.qcloudLVB.Assistant;
import com.hboxs.asl.qcloudLVB.Conf;
import com.hboxs.asl.qcloudLVB.Constants;
import com.hboxs.asl.qcloudLVB.entity.Live;
import com.hboxs.asl.qcloudLVB.service.LiveService;
import com.hboxs.asl.qcloudLVB.util.QcloudDateUtils;
import com.hboxs.asl.qcloudLVB.util.SafeUrlUtils;
import com.hboxs.asl.service.*;
import com.hboxs.asl.util.DateUtils;
import com.hboxs.asl.wechat.utils.HttpClientUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by xxx on 10/12/2016.
 * <p>
 * Controller -- 前端接口
 * <p>
 */
@Controller(value = "appLiveController")
@RequestMapping(value = "/app/live")
public final class LiveController extends BaseController {

    //直播流开关状态( 0:关闭； 1:开启 )
    private static final int LIVE_ONLINE = 1;
    private static final int LIVE_OFFLINE = 0;

    protected Logger logger = Logger.getLogger(getClass());

    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "liveServiceImpl")
    private LiveService liveService;
    @Resource(name = "courseServiceImpl")
    private CourseService courseService;
    @Resource(name = "courseTradeServiceImpl")
    private CourseTradeService courseTradeService;
    @Resource(name = "liveGiftServiceImpl")
    private LiveGiftService liveGiftService;
    @Resource(name = "globalConfigServiceImpl")
    private GlobalConfigService globalConfigService;
    @Resource(name = "robotServiceImpl")
    private RobotService robotService;


    @RequestMapping(value = "add_funs", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage addFuns(Long liveId) {
        synchronized (this) {
            Live live = liveService.find(liveId);
            if (live == null) {
                return JsonMessage.error("课程已下线");
            }
            //获取所有机器人
            List<Robot> robotList = robotService.findAll();

            //获取观看过直播的机器人
            Set<Robot> robotSet = live.getWatchedRobots();
            //保存机器人
            List<Robot> robots = new ArrayList<>();
            if (robotSet.size() > 1) {
                //获取随机数
                Random random = new Random();
                //随机生成一个数在1-3之间
                int randomNumber = random.nextInt(3)+1;
                for (int i = 0; i<randomNumber; i++) {
                    //random.nextInt(robotList.size())对象在robotList中的位置
                    int index = random.nextInt(robotList.size());
                    if(!robotSet.contains(robotList.get(index))) {
                        robots.add(robotList.get(index));
                    }
                }
            } else {
                //获取随机数
                Random random = new Random();
                //随机生成一个数在1-3之间
                int randomNumber = random.nextInt(3)+1;
                for (int i = 0; i<randomNumber; i++) {
                    //random.nextInt(robotList.size())对象在robotList中的位置
                    robots.add(robotList.get(random.nextInt(robotList.size())));
                }
            }
            robotSet.addAll(robots);
            //保存刚添加的机器人
            live.setWatchedRobots(robotSet);
            liveService.save(live);
            return JsonMessage.success(JsonMessage.optimiseObj(robots, "id", "name", "avator"));
        }
    }








    /**
     * 获取当前正在观看的用户
     * @param liveId
     * @return
     */
    @RequestMapping(value = "watching_members", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage watchingMembers(Long liveId) {
        try {
            Live live = liveService.find(liveId);
            if (live == null) {
                return JsonMessage.error("课程已下架");
            }
            if (!Live.LiveStatus.live.equals(live.getLiveStatus()) || live.getAnchor() == null) {
                return JsonMessage.error("直播已关闭");
            }
            List<Member> memberList = new ArrayList<>(live.getGroup());
            return JsonMessage.success(JsonMessage.optimiseObj(memberList, "id", "name", "avator"));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }


    /**
     * 添加假粉数
     * @param liveId
     * @param count
     * @return
     */
    @RequestMapping(value = "add_robots", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage addRobots(Long liveId, Long count) {
        try {
            synchronized (this) {
                Live live = liveService.find(liveId);
                if (live == null) {
                    return JsonMessage.error("课程已下架");
                }
                //添加观看假粉数
                if (live.getHisRobots() == null) {
                    live.setHisRobots(count);
                } else {
                    live.setHisRobots(live.getHisRobots() + count);
                }
                liveService.update(live);
                return JsonMessage.success();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }


    /**
     * 获取机器人
     * @return
     */
    @RequestMapping(value = "robots", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage Robots() {
        List<Robot> robots = robotService.findAll();
        Collections.shuffle(robots);
        return JsonMessage.success(JsonMessage.optimiseObj(robots, "avator", "name"));
    }

    /**
     * 获取直播是否开放
     * @return
     */
    @RequestMapping(value = "/onOff", method = RequestMethod.GET)
    public
    @ResponseBody
    Object onOff() {
        GlobalConfig globalConfig = globalConfigService.getUniqueness();

        return JsonMessage.success(

                "onOff", globalConfig.getOnOff(),

                "payShow", globalConfig.getPayShow(),

                "percentage", globalConfig.getPercentage()
        );
    }

    /**
     * 判断当前用户与主播的关系
     * @param courseId
     * @return
     */
    @RequestMapping(value = "/correlation", method = RequestMethod.GET)
    public
    @ResponseBody
    Object correlation(Long courseId, String password) {
        try {
            if (password == null) {
                Member member = memberService.getCurrentByToken();
                if (member == null) {
                    return JsonMessage.USER_NOT_LOGIN;
                }
                Course course = courseService.find(courseId);
                if (course == null) {
                    return JsonMessage.error("课程不存在");
                }

                Live live = course.getLive();

                Member anchor = live.getAnchor();

                boolean follow = false;
                if (anchor != null) {
                    //判断当前用户与主播的关系
                    Set<Member> memberSet = anchor.getFavorMembers();
                    if (memberSet.contains(member)) {
                        follow = true;
                    }
                }

                return JsonMessage.success(
                        "follow", follow,
                        "anchorId", live.getAnchor().getId(),
                        "anchorName", live.getAnchor().getName(),
                        "videoURL", live.getVideoURL(),
                        "liveId", live.getId()
                );
            } else {
                Member member = memberService.getCurrentByToken();
                if (member == null) {
                    return JsonMessage.USER_NOT_LOGIN;
                }
                Course course = courseService.find(courseId);

                if (!course.getPassword().equals(password)) {
                    return JsonMessage.error("密码错误");
                }

                if (course == null) {
                    return JsonMessage.error("课程不存在");
                }

                Live live = course.getLive();

                Member anchor = live.getAnchor();

                boolean follow = false;
                if (anchor != null) {
                    //判断当前用户与主播的关系
                    Set<Member> memberSet = anchor.getFavorMembers();
                    if (memberSet.contains(member)) {
                        follow = true;
                    }
                }

                return JsonMessage.success(
                        "follow", follow,
                        "anchorId", live.getAnchor().getId(),
                        "anchorName", live.getAnchor().getName(),
                        "videoURL", live.getVideoURL(),
                        "liveId", live.getId()
                );
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 直播(status==live)列表(用户端)
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public
    @ResponseBody
    Object index(Pageable pageable) {
        try {
            Member member = memberService.getCurrentByToken();
            if(member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            //查找正在直播的直播
            pageable.setOrderDirection(Order.Direction.desc);

            pageable.getFilters().add(Filter.ne("type", Live.Type.connection));

            Page page = liveService.findPage(pageable, Live.LiveStatus.live, Live.Type.host);

            return JsonMessage.success(

                    JsonMessage.optimiseObj(

                            page, "pageNumber", "pageSize", "totalPages", "total",

                            "content.id#cover#title#anchor.id#anchor.usernameHide#anchor.avator#anchor.name#watchCount#admireCount"

                    )
            );
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 直播录制回调
     */
    @RequestMapping(value = "/notify.htm", method = RequestMethod.POST)
    public
    @ResponseBody
    Object notify(@RequestBody JSONObject notify) {

        try {

                // 判断断流 、 录制
                // event_type	int	事件类型	目前可能值为： 0、1、100、200 event_type = 0 代表断流，event_type = 1 代表推流，event_type = 100 代表有新的录制文件生成
                Integer event_type = notify.getInteger("event_type");
                // 直播的房間id
                String stream_id = notify.getString("stream_id");

            synchronized (stream_id.intern()) {
                if (event_type == 100) {

                    // 录制结果的视频url
                    String video_url = notify.getString("video_url");

                    if (!StringUtils.isEmpty(video_url)) {

                        String liveId = stream_id.substring(stream_id.lastIndexOf("_")+1);
                        Live live = liveService.find(Long.parseLong(liveId));
                        if (live != null) {
                            if(video_url.contains(".mp4")) {    //mp4
                                String mp4URL = live.getMp4URL();
                                if (!StringUtils.isEmpty(mp4URL)) {
                                    mp4URL = mp4URL+Constant.SPILT+video_url;
                                    live.setMp4URL(mp4URL);
                                } else {
                                    live.setMp4URL(video_url);
                                }
                                liveService.update(live);
                            } else {                        //m3u8
                                //分片开始时间戳
                                long start_time = notify.getLongValue("start_time");
                                //分片结束时间戳
                                long end_time = notify.getLongValue("end_time");
                                //录制视频时长时间戳
                                Long time = (end_time - start_time)*1000;

                                System.out.println("录制时间：" + time + "  当前时间" + DateUtils.long2Date(System.currentTimeMillis()));

                                //设置时间
                                live.setTimeSpan(time);
                                //设置url
                                live.setVideoURL(video_url);
                                liveService.update(live);
                            }
                        }
                    }
                }

                if (event_type == 0) {

                    //1,2主播端主动断流 3主播端主动断开TCP连接
                    Integer errcode = notify.getInteger("errcode");
                    if (errcode == 1 || errcode == 2 || errcode == 3) {
                        String liveId = stream_id.substring(stream_id.lastIndexOf("_")+1);

                        Live live = liveService.find(Long.parseLong(liveId));

                        if (live != null) {
                            //小主播断流
                            if (live.getConnectLiveId() != null) {
                                live.setLiveStatus(Live.LiveStatus.finished);
                                liveService.update(live);
                                //获取大主播直播id
                                Long connectLiveId = live.getConnectLiveId();
                                Live anchorLive = liveService.find(connectLiveId);
                                String postJson = getJsonTest("Mix_StreamV2", anchorLive);
                                Long t = QcloudDateUtils.getTxTime(Constants.API_CALL_TXTIME);
                                String url = Conf.API_CALL_URL + "?cmd=" + Conf.APPID + "&interface=Mix_StreamV2&t=" + t.toString() + "&sign=" + SafeUrlUtils.getSign(t);
                                HttpClientUtils.post(url, postJson);
                            }
                        }

                    }
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonMessage.success();
    }


    /**
     * 用户端:直播内容
     *
     * @param courseId 课程courseId
     * @return json
     */
    @RequestMapping(value = "/content", method = RequestMethod.POST)
    public
    @ResponseBody
    Object content(Long courseId, String password, String touristId) {

        try {

            //观众
            Member member = memberService.getCurrentByToken();
            if(member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }

            Course course = courseService.find(courseId);
            if (course == null) {
                return JsonMessage.error("课程不存在");
            }

            //判断分享出去的密码是否正确
            if (password != null) {
                if (!course.getPassword().equals(password)) {
                    return JsonMessage.error("密码错误");
                }
            }

            if (touristId != null) {
                member.setTouristId(touristId);
                memberService.update(member);
            }

            Live live = course.getLive();

            if (live == null) {
                return JsonMessage.error("直播不存在");
            }

            if (!Live.LiveStatus.live.equals(live.getLiveStatus()) || live.getAnchor() == null) {
                return JsonMessage.error("直播已关闭");
            }

            //获取播放地址
            Map<String, String> map = liveService.getPlayUrl(Conf.BIZID, live.getId().toString());

            liveService.changeCount(live.getAnchor(), member, 0, 0, 0, null);

            return JsonMessage.success(

                    //直播url
                    "playUrl", map,

                    "isLogin", member != null, "isFocus", member.getFavorAnchors().contains(live.getAnchor())

                    //直播数据
                    , "live",
                    JsonMessage.optimiseObj(
                            live, "id", "cover", "title", "watchCount", "groupid",
                            "anchor.id", "anchor.avator", "anchor.name", "anchor.touristId"
                    )

                    //直播观看成员
                    , "viewers", JsonMessage.optimiseObj(live.getGroup(), "id", "username", "avator")

            );
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;

    }

    /**
     * 获取连麦小窗口播放地址
     */
    @RequestMapping(value = "/connectLivePlayUrl", method = RequestMethod.GET)
    public
    @ResponseBody
    Object connectLivePlayUrl(Long liveId){
        Member member = memberService.getCurrentByToken();
        if (member == null) {
            return JsonMessage.USER_NOT_LOGIN;
        }
        //小主播的直播
        Live live = liveService.find(liveId);
        Long connectLiveId = live.getConnectLiveId();
        //大主播的直播
        Live connectLive = liveService.find(connectLiveId);
        if (connectLive==null){
            return JsonMessage.error("没有连麦直播");
        }
        if (!Live.LiveStatus.live.equals(connectLive.getLiveStatus()) || connectLive.getAnchor() == null) {
            return JsonMessage.error("直播已关闭");
        }
        Map<String, String> map = liveService.getPlayUrl(Conf.BIZID, live.getId().toString());

        return JsonMessage.success(map);
    }

    /**
     * 接口获取混流
     */
    @RequestMapping(value = "/mixed_flow", method = RequestMethod.GET)
    public
    @ResponseBody
    Object mixedFlow(Long liveId) {

        //获取所有正在直播中的连麦
        Live live = liveService.find(liveId);
        if (live == null) {
            return JsonMessage.error("视频不存在");
        }

        List<Live> connectedLives = liveService.findConnectLive(liveId, Live.LiveStatus.live);
        String postJson = getJsonByLiveId("Mix_StreamV2", connectedLives, live);
        Long t = QcloudDateUtils.getTxTime(Constants.API_CALL_TXTIME);
        String url = Conf.API_CALL_URL + "?cmd=" + Conf.APPID + "&interface=Mix_StreamV2&t=" + t.toString() + "&sign=" + SafeUrlUtils.getSign(t);
        HttpClientUtils.post(url, postJson);
        //拼装主播推流url
        String pushurl = liveService.getPushUrl(Conf.BIZID, live.getId().toString(), Conf.PUSH_KEY, QcloudDateUtils.getTxTime(Constants.PUSH_TXTIME));

        //获取主播拉流
        Map<String, String> map = liveService.getPlayUrl(Conf.BIZID, live.getId().toString());
        return JsonMessage.success(
                "pushurl", pushurl,
                "playurl", map
        );
    }

    public String getJsonTest(String interfaceName, Live live) {

        Long time = Calendar.getInstance().getTime().getTime();

        String liveJson = " {                                                                                        "+
                "     \"timestamp\":"+ time +",                      "+
                "     \"eventId\":"+ time +",                        "+
                "     \"interface\":                                                                      "+
                "     {                                                                                   "+
                "         \"interfaceName\":\""+interfaceName+"\",                                             "+
                "         \"para\":                                                                       "+
                "         {                                                                               "+
                "             \"app_id\": "+Conf.APPID+",                                                 "+
                "             \"interface\": \"mix_streamv2.start_mix_stream_advanced\",                  "+
                "             \"mix_stream_session_id\" : \""+Assistant.getStreamId(Conf.BIZID, live) +"\",     "+
                "             \"output_stream_id\": \""+Assistant.getStreamId(Conf.BIZID, live) +"\",           "+
                "             \"input_stream_list\":                                                      "+
                "             [                                                                           ";

        String zhibo = "";

        String dazhubo = "                 {                                                                       "+
                "                     \"input_stream_id\":\" " + Assistant.getStreamId(Conf.BIZID, live)  + " \",                                 "+
                "                     \"layout_params\":                                                  "+
                "                     {                                                                   "+
                "                         \"image_layer\": 1                                              "+
                "                     }                                                                   "+
                "                 }                                                                     ";

        zhibo += dazhubo;
        liveJson += zhibo + "             ]                                                                           "+
                "         }                                                                               "+
                "     }                                                                                   "+
                " }                                                                                       ";
        return liveJson;
    }

    /**
     * 房间号：直播码+"_"+liveId
     * @param interfaceName
     * @param lives
     * @param live
     * @return
     */
    public String getJsonByLiveId(String interfaceName, List<Live> lives, Live live) {

        Long time = Calendar.getInstance().getTime().getTime();

        String liveJson = " {                                                                                        "+
                "     \"timestamp\":"+ time +",                      "+
                "     \"eventId\":"+ time +",                        "+
                "     \"interface\":                                                                      "+
                "     {                                                                                   "+
                "         \"interfaceName\":\""+interfaceName+"\",                                             "+
                "         \"para\":                                                                       "+
                "         {                                                                               "+
                "             \"app_id\": "+Conf.APPID+",                                                 "+
                "             \"interface\": \"mix_streamv2.start_mix_stream_advanced\",                  "+
                "             \"mix_stream_session_id\" : \""+Assistant.getStreamId(Conf.BIZID, live) +"\",     "+
                "             \"output_stream_id\": \""+Assistant.getStreamId(Conf.BIZID, live)+"\",           "+
                "             \"input_stream_list\":                                                      "+
                "             [                                                                           ";

        String zhibo = "";
        if (lives.size() > 0) {

            String dazhubo = "                 {                                                                       "+
                    "                     \"input_stream_id\":\" " + Assistant.getStreamId(Conf.BIZID, live)   + " \",                                 "+
                    "                     \"layout_params\":                                                  "+
                    "                     {                                                                   "+
                    "                         \"image_layer\": 1                                              "+
                    "                     }                                                                   "+
                    "                 },                                                                      ";

            zhibo += dazhubo;
            for (int i=0; i<lives.size(); i++) {
                if (i == 0) {
                    String xiaozhubo = "";
                    if (i == lives.size()-1) {


                        xiaozhubo = "                 {                                                                       "+
                                "                     \"input_stream_id\":\""+ Assistant.getStreamId(Conf.BIZID, lives.get(i))  +"\",                                   "+
                                "                     \"layout_params\":                                                  "+
                                "                     {                                                                   "+
                                "                         \"image_layer\": 2,                                             "+
                                "                         \"image_width\": 160,                                           "+
                                "                         \"image_height\": 240,                                          "+
                                "                         \"location_x\": 380,                                            "+
                                "                         \"location_y\": 630                                             "+
                                "                     }                                                                   "+
                                "                  }                                                                     ";

                    } else {

                        xiaozhubo = "                 {                                                                       "+
                                "                     \"input_stream_id\":\""+ Assistant.getStreamId(Conf.BIZID, lives.get(i))  +"\",                                   "+
                                "                     \"layout_params\":                                                  "+
                                "                     {                                                                   "+
                                "                         \"image_layer\": 2,                                             "+
                                "                         \"image_width\": 160,                                           "+
                                "                         \"image_height\": 240,                                          "+
                                "                         \"location_x\": 380,                                            "+
                                "                         \"location_y\": 630                                             "+
                                "                     }                                                                   "+
                                "                  },                                                                     ";

                    }
                    zhibo += xiaozhubo;
                } else if (i == 1) {
                    String xiaozhubo = "";
                    if (i == lives.size()-1) {


                        xiaozhubo = "                 {                                                                       "+
                                "                     \"input_stream_id\":\""+ Assistant.getStreamId(Conf.BIZID, lives.get(i))  +"\",                                   "+
                                "                     \"layout_params\":                                                  "+
                                "                     {                                                                   "+
                                "                         \"image_layer\": 3,                                             "+
                                "                         \"image_width\": 160,                                           "+
                                "                         \"image_height\": 240,                                          "+
                                "                         \"location_x\": 380,                                            "+
                                "                         \"location_y\": 630                                             "+
                                "                     }                                                                   "+
                                "                  }                                                                     ";

                    } else {

                        xiaozhubo = "                 {                                                                       "+
                                "                     \"input_stream_id\":\""+ Assistant.getStreamId(Conf.BIZID, lives.get(i)) +"\",                                   "+
                                "                     \"layout_params\":                                                  "+
                                "                     {                                                                   "+
                                "                         \"image_layer\": 3,                                             "+
                                "                         \"image_width\": 160,                                           "+
                                "                         \"image_height\": 240,                                          "+
                                "                         \"location_x\": 380,                                            "+
                                "                         \"location_y\": 630                                             "+
                                "                     }                                                                   "+
                                "                  },                                                                     ";

                    }
                    zhibo += xiaozhubo;
                } else if (i == 2) {
                    String xiaozhubo = "";
                    if (i == lives.size()-1) {


                        xiaozhubo = "                 {                                                                       "+
                                "                     \"input_stream_id\":\""+ Assistant.getStreamId(Conf.BIZID, lives.get(i))  +"\",                                   "+
                                "                     \"layout_params\":                                                  "+
                                "                     {                                                                   "+
                                "                         \"image_layer\": 4,                                             "+
                                "                         \"image_width\": 160,                                           "+
                                "                         \"image_height\": 240,                                          "+
                                "                         \"location_x\": 380,                                            "+
                                "                         \"location_y\": 630                                             "+
                                "                     }                                                                   "+
                                "                  }                                                                     ";

                    } else {

                        xiaozhubo = "                 {                                                                       "+
                                "                     \"input_stream_id\":\""+ Assistant.getStreamId(Conf.BIZID, lives.get(i))  +"\",                                   "+
                                "                     \"layout_params\":                                                  "+
                                "                     {                                                                   "+
                                "                         \"image_layer\": 4,                                             "+
                                "                         \"image_width\": 160,                                           "+
                                "                         \"image_height\": 240,                                          "+
                                "                         \"location_x\": 380,                                            "+
                                "                         \"location_y\": 630                                             "+
                                "                     }                                                                   "+
                                "                  },                                                                     ";

                    }
                    zhibo += xiaozhubo;
                } else {
                    break;
                }
            }
        }
        liveJson += zhibo + "             ]                                                                           "+
                "         }                                                                               "+
                "     }                                                                                   "+
                " }                                                                                       ";
        return liveJson;
    }


    /**
     * 主播信息
     */
    @RequestMapping(value = "/anchor_info", method = RequestMethod.GET)
    public
    @ResponseBody
    Object anchorInfo(Long id) {
        try {
            Member member = memberService.getCurrentByToken();
            if(member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Live live = liveService.find(id);
            if (live == null) return JsonMessage.error("直播不存在");
            Member anchor = live.getAnchor();
            return JsonMessage.success("anchor", JsonMessage.optimiseObj(anchor, "id", "username", "name", "avator"));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 关闭直播
     *
     * @param id 直播id
     * @return json
     */
    @RequestMapping(value = "/close", method = RequestMethod.POST)
    public
    @ResponseBody
    Object close(Long id) {

        Live live = liveService.find(id);
        if (live == null) {
            return JsonMessage.success("直播不存在");
        }
        Member anchor = live.getAnchor();

        if (!Live.LiveStatus.live.equals(live.getLiveStatus()) || anchor == null) {
            return JsonMessage.success("直播已关闭");
        }

        Member member = memberService.getCurrentByToken();

        //主播主动关闭直播
        if (anchor.getId().equals(member.getId())) {
            //断开连接
            liveService.disConnect(live);
            Boolean ret = liveService.changeStatus(LIVE_OFFLINE, live.getId());
            if (!ret) {
                return JsonMessage.UNKNOWN_ERROR;
            }
            //主播下线，清空正在观看的用户
            liveService.clearWatchingMembers(live);
            Course course = live.getCourse();
            if (course != null) {
                //修改课程状态
                course.setCourseType(Course.CourseType.finished);
                courseService.update(course);
                //批量更新课程交易状态
                courseTradeService.updateBatch(course.getId(), CourseTrade.CourseType.finished);
            }
        }

        //登陆用户关闭直播
        if (member != null && !anchor.equals(member)) {
            liveService.changeCount(live.getAnchor(), memberService.getCurrentByToken(), 0, 1, 0, null);
        }

        return JsonMessage.success();
    }

    /**
     * 修改流状态
     *
     * @return code
     */
    @RequestMapping(value = "/changeStatus", method = RequestMethod.POST)
    public
    @ResponseBody
    Object changeStatus(int status, Long liveId) {

        try {

            Member member = memberService.getCurrentByToken();

            if(member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }

            Live live = liveService.find(liveId);
            if (live == null) {
                return JsonMessage.error("直播不存在");
            }
            if (live.getLiveStatus() != null && (Live.LiveStatus.finished.equals(live.getLiveStatus()) || Live.LiveStatus.forbidden.equals(live.getLiveStatus()))) {
                return JsonMessage.error("直播已结束");
            }

            Boolean ret = liveService.changeStatus(status, liveId);

            return ret ? JsonMessage.success() : JsonMessage.error("修改状态失败");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;


    }

    /**
     * 获取直播状态
     *
     * @param liveId 直播id
     * @return json
     */
    @RequestMapping(value = "/getLiveStatus", method = RequestMethod.POST)
    public
    @ResponseBody
    Object getLiveStatus(Long liveId) {
        Live live = liveService.find(liveId);
        return live == null ? JsonMessage.error("直播不存在") : JsonMessage.success(live.getLiveStatus().toString());
    }

    /**
     * 拉取群成员列表 fetchGroupMemberList
     *
     * @param id       直播id
     * @param pageable 分页信息
     */
    @RequestMapping(value = "/fetchGroupMemberList", method = RequestMethod.POST)
    public
    @ResponseBody
    Object fetchGroupMemberList(Long id, Pageable pageable, Integer status) {
        Live live = liveService.find(id);

        if (status == null) {
            pageable.getFilters().add(Filter.eq("watchingLive", live));
            Page<Member> page = memberService.findPage(pageable);

            //获取最多前20个
            List<Member> memberList = new ArrayList<>();
//            if (page.getContent().size() > 20) {
//                memberList = page.getContent().subList(0,20);
//            } else {
            memberList = page.getContent();
//            }

            //获取机器人数
            List<Robot> robotSet = new ArrayList<>(live.getWatchedRobots());
            List<Robot> robotList = new ArrayList<>();
            if (robotSet.size() > 20) {
                robotList = robotSet.subList(0, 20);
                return JsonMessage.success(

                        "watchCount", live.getWatchCount(),//当前观看人数

                        "groupid", live.getGroupid(),

                        "robotSet", JsonMessage.optimiseObj(robotList, "id", "name", "avator"),

                        "memberList", JsonMessage.optimiseObj(memberList, "id", "name", "avator")
                );
            } else {
                return JsonMessage.success(

                        "watchCount", live.getWatchCount(),//当前观看人数

                        "groupid", live.getGroupid(),

                        "robotSet", JsonMessage.optimiseObj(robotSet, "id", "name", "avator"),

                        "memberList", JsonMessage.optimiseObj(memberList, "id", "name", "avator")

                );
            }
        } else {
            if (status == 0) {   //录播中的

                Page<Member> page = memberService.findPageLive(pageable, live);

                //获取最多前20个
                List<Member> memberList = new ArrayList<>();
//            if (page.getContent().size() > 20) {
//                memberList = page.getContent().subList(0,20);
//            } else {
                memberList = page.getContent();
//            }

                //获取机器人数
                List<Robot> robotSet = new ArrayList<>(live.getWatchedRobots());
                List<Robot> robotList = new ArrayList<>();
                if (robotSet.size() > 20) {
                    robotList = robotSet.subList(0, 20);
                    return JsonMessage.success(

                            "watchCount", live.getHisWatchCount(),//历史观看人数

                            "groupid", live.getGroupid(),

                            "robotSet", JsonMessage.optimiseObj(robotList, "id", "name", "avator"),

                            "memberList", JsonMessage.optimiseObj(memberList, "id", "name", "avator")
                    );
                } else {
                    return JsonMessage.success(

                            "watchCount", live.getHisWatchCount(),//历史观看人数

                            "groupid", live.getGroupid(),

                            "robotSet", JsonMessage.optimiseObj(robotSet, "id", "name", "avator"),

                            "memberList", JsonMessage.optimiseObj(memberList, "id", "name", "avator")
                    );
                }

            } else {                //直播中的
                pageable.getFilters().add(Filter.eq("watchingLive", live));
                Page<Member> page = memberService.findPage(pageable);

                //获取最多前20个
                List<Member> memberList = new ArrayList<>();
//            if (page.getContent().size() > 20) {
//                memberList = page.getContent().subList(0,20);
//            } else {
                memberList = page.getContent();
//            }

                //获取机器人数
                List<Robot> robotSet = new ArrayList<>(live.getWatchedRobots());
                List<Robot> robotList = new ArrayList<>();
                if (robotSet.size() > 20) {
                    robotList = robotSet.subList(0, 20);
                    return JsonMessage.success(

                            "watchCount", live.getWatchCount(),//当前观看人数

                            "groupid", live.getGroupid(),

                            "robotSet", JsonMessage.optimiseObj(robotList, "id", "name", "avator"),

                            "memberList", JsonMessage.optimiseObj(memberList, "id", "name", "avator")
                    );
                } else {
                    return JsonMessage.success(

                            "watchCount", live.getWatchCount(),//当前观看人数

                            "groupid", live.getGroupid(),

                            "robotSet", JsonMessage.optimiseObj(robotSet, "id", "name", "avator"),

                            "memberList", JsonMessage.optimiseObj(memberList, "id", "name", "avator")

                    );
                }
            }
        }
    }

    /**
     * 获取礼物列表
     * @return
     */
    @RequestMapping(value = "/gifts", method = RequestMethod.GET)
    public
    @ResponseBody
    Object gifts() {
        try {

            List<LiveGift> liveGifts = liveGiftService.findAll();

            return JsonMessage.success(JsonMessage.optimiseObj(liveGifts, "id", "name", "coin", "order", "image"));

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

}